
package com.afd.ozblip.activity;

import java.util.HashMap;
import java.util.Map;

import com.afd.ozblip.chat.ChatClient;
import com.afd.ozblip.entity.UserEntity;
import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.ParseJson;
import com.afd.ozblip.util.SharedUtil;
import com.afd.ozblip.util.StringUtil;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class TabLoginActivity extends BaseActivity {

    /****************** 视图变量 **************************/
    private LinearLayout commonRight;
    private Button loginBtn;
    private ImageView qqIv;
    private ImageView weiboIv;
    private ImageView twitterIv;
    private ImageView facebookIv;
    private EditText emailEt;
    private EditText passwordEt;

    /****************** 普通变量 **************************/
    private String userNameStr;
    private String passwordStr;
    private UserEntity userInfo;

    /****************** 第三方登录变量 **************************/
    /*
     * 申请APP KEY的具体介绍，可参见 http://wiki.open.t.qq.com/index.php/应用接入指引
     * http://wiki.
     * open.t.qq.com/index.php/腾讯微博移动应用接入规范#.E6.8E.A5.E5.85.A5.E6.B5.81.E7.A8.8B
     */
    // !!!请根据您的实际情况修改!!! 认证成功后浏览器会被重定向到这个url中 必须与注册时填写的一致
    private String redirectUri = "http://www.tencent.com/zh-cn/index.shtml";
    // !!!请根据您的实际情况修改!!! 换为您为自己的应用申请到的APP KEY
    private String clientId = "801115505";
    // !!!请根据您的实际情况修改!!! 换为您为自己的应用申请到的APP SECRET
    private String clientSecret = "be1dd1410434a9f7d5a2586bab7a6829";

    private OAuthV2 oAuth;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        // 启动返回功能
        toBack();
        // 寻找视图
        findViews();
        // 设置监听
        setListeners();
        // 获取参数
        getBundle();
    }

    /**
     * 寻找视图
     */
    public void findViews() {
        this.commonRight = (LinearLayout) findViewById(R.id.ll_common_right);
        this.loginBtn = (Button) findViewById(R.id.btn_user_login);
        this.facebookIv = (ImageView) findViewById(R.id.iv_login_facebook);
        this.twitterIv = (ImageView) findViewById(R.id.iv_login_twitter);
        this.weiboIv = (ImageView) findViewById(R.id.iv_login_weibo);
        this.qqIv = (ImageView) findViewById(R.id.iv_login_qq);
        this.emailEt = (EditText) findViewById(R.id.et_login_email);
        this.passwordEt = (EditText) findViewById(R.id.et_login_password);
        // 读取原来登录成功的邮箱
        String emailStr = SharedUtil.fetchLoginInfo(this);
        if (!StringUtil.isNullOrEmpty(emailStr)) {
            this.emailEt.setText(emailStr);
            this.passwordEt.requestFocus();
        }
    }

    /**
     * 设置监听
     */
    public void setListeners() {
        View.OnClickListener loginClick = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent;
                switch (v.getId()) {
                    case R.id.ll_common_right:
                        Intent registerIntent = new Intent(TabLoginActivity.this,
                                RegisterActivity.class);
                        startActivity(registerIntent);
                        break;
                    case R.id.btn_user_login:
                        userNameStr = emailEt.getText().toString();
                        passwordStr = passwordEt.getText().toString();
                        if (verifyData()) {
                            requestLoginInfo();
                        }
                        break;
                    case R.id.iv_login_qq:
                        oAuth = new OAuthV2(redirectUri);
                        oAuth.setClientId(clientId);
                        oAuth.setClientSecret(clientSecret);
                        intent = new Intent(TabLoginActivity.this,
                                OAuthV2AuthorizeWebView.class);// 创建Intent，使用WebView让用户授权
                        intent.putExtra("oauth", oAuth);
                        startActivityForResult(intent, 2);

                        break;

                    default:
                        break;
                }
            }
        };
        this.commonRight.setOnClickListener(loginClick);
        this.loginBtn.setOnClickListener(loginClick);
        this.facebookIv.setOnClickListener(loginClick);
        this.twitterIv.setOnClickListener(loginClick);
        this.weiboIv.setOnClickListener(loginClick);
        this.qqIv.setOnClickListener(loginClick);
    }

    /**
     * 获取传递的参数
     */
    private void getBundle() {
        Intent intent = getIntent();
    }

    /**
     * 验证数据有效性
     */
    private boolean verifyData() {
        if (StringUtil.isNullOrEmpty(userNameStr)) {
            Toast.makeText(TabLoginActivity.this, "温馨提示：请输入用户名!",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        if (StringUtil.isNullOrEmpty(passwordStr)) {
            Toast.makeText(TabLoginActivity.this, "温馨提示：请输入密码!",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        if (passwordStr.length() < 6) {
            Toast.makeText(TabLoginActivity.this, "温馨提示：密码长度不够!",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 用户注册数据提交
     * 
     * @param paramString
     */
    public void requestLoginInfo() {
        AsyncLoadData ald = new AsyncLoadData(this, "正在登录...",
                new AsyncAction() {
                    @Override
                    public void doLoad() throws Exception {
                        // 获取提交参数
                        Map<String, Object> registerParamMap = new HashMap<String, Object>();
                        registerParamMap.put("userName", userNameStr);
                        // passwordStr =
                        // StringUtil.getMD5Str(passwordStr);服务器已MD5加密
                        registerParamMap.put("passWord", passwordStr);
                        // 发送请求
                        byte[] bUserRegiter = HttpUtil.requestByPost(
                                TabLoginActivity.this, Constants.USER_LOGIN_API,
                                registerParamMap);
                        if (bUserRegiter != null) {
                            userInfo = new ParseJson()
                                    .parseUserInfoJson(bUserRegiter);
                        }
                    }

                    @Override
                    public void loadEnd() throws Exception {
                        if (userInfo != null) {
                            boolean loginFlg = userInfo.getLogintResult();
                            if (loginFlg) {
                                showShortToast(TabLoginActivity.this, "登录成功", true);
                                Intent indexIntent = new Intent(
                                        TabLoginActivity.this, IndexActivity.class);
                                indexIntent.putExtra(
                                        IndexActivity.INTENT_TAB_CHANGE, 3);
                                isLogin = true;
                                commonUserInfo = userInfo;
                                // 开起chat对话连接
                                new Thread(new Runnable() {
                                    public void run() {
                                        ChatClient.getInstances(userInfo
                                                .getUserId());
                                    }
                                }).start();
                                startActivity(indexIntent);
                                // 存储用户名，方便下一次登录
                                // SharedUtil.storeLoginInfo(TabLoginActivity.this,
                                // userNameStr,userInfo);
                                finish();
                            } else {
                                showShortToast(TabLoginActivity.this,
                                        userInfo.getLoginMessage(), true);
                            }
                        }
                    }
                });
        ald.execute(0);
    }

    /*
     * 通过读取OAuthV2AuthorizeWebView返回的Intent，获取用户授权信息
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 2) {
            if (resultCode == OAuthV2AuthorizeWebView.RESULT_CODE) {
                oAuth = (OAuthV2) data.getExtras().getSerializable("oauth");
                if (oAuth.getStatus() == 0) {
                    Toast.makeText(getApplicationContext(), "登陆成功",
                            Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}
